{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "pycharm": {
     "is_executing": false
    }
   },
   "source": [
    "## Simple linear regression"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 构造简单的训练样本\n",
    "x_train = torch.rand(100)\n",
    "y_train = x_train * 2 + 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 初始化w, b\n",
    "w = torch.tensor([0.0], requires_grad=True)\n",
    "b = torch.tensor([0.0], requires_grad=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def loss_func(y_true: torch.Tensor, y_pre: torch.Tensor):\n",
    "    square = (y_true - y_pre) ** 2\n",
    "    return square.mean()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def train():\n",
    "    lr = 0.3\n",
    "    for i in range(10):\n",
    "        y_pre = x_train * w + b\n",
    "        loss = loss_func(y_train, y_pre)\n",
    "        loss.backward()\n",
    "\n",
    "        # 更新\n",
    "        w.data -= w.grad * lr\n",
    "        b.data -= b.grad * lr\n",
    "\n",
    "        # 清除梯度值\n",
    "        w.grad.data.zero_()\n",
    "        b.grad.data.zero_()\n",
    "\n",
    "        print('Epoch {}, loss is {:.4f}. w = {:.2f}, b = {:.2f}'.format(i, loss.item(), w.item(), b.item()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 0, loss is 16.9771. w = 1.42, b = 2.45\n",
      "Epoch 1, loss is 0.7747. w = 1.73, b = 2.97\n",
      "Epoch 2, loss is 0.0380. w = 1.80, b = 3.08\n",
      "Epoch 3, loss is 0.0043. w = 1.82, b = 3.10\n",
      "Epoch 4, loss is 0.0026. w = 1.83, b = 3.10\n",
      "Epoch 5, loss is 0.0023. w = 1.84, b = 3.09\n",
      "Epoch 6, loss is 0.0022. w = 1.84, b = 3.09\n",
      "Epoch 7, loss is 0.0020. w = 1.85, b = 3.09\n",
      "Epoch 8, loss is 0.0019. w = 1.85, b = 3.08\n",
      "Epoch 9, loss is 0.0017. w = 1.86, b = 3.08\n"
     ]
    }
   ],
   "source": [
    "train()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Pytorch的套路"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SimpleLinear:\n",
    "    def __init__(self):\n",
    "        self.w = torch.tensor([0.0], requires_grad=True)\n",
    "        self.b = torch.tensor([0.0], requires_grad=True)\n",
    "\n",
    "    def forward(self, x):\n",
    "        y = self.w * x + self.b\n",
    "        return y\n",
    "\n",
    "    def parameters(self):\n",
    "        return [self.w, self.b]\n",
    "\n",
    "    def __call__(self, x):\n",
    "        return self.forward(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Optimizer:\n",
    "    def __init__(self, parameters, lr):\n",
    "        self.parameters = parameters\n",
    "        self.lr = lr\n",
    "\n",
    "    def step(self):\n",
    "        for para in self.parameters:\n",
    "            para.data -= para.grad * self.lr\n",
    "\n",
    "    def zero_grad(self):\n",
    "        for para in self.parameters:\n",
    "            para.grad.data.zero_()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 0, loss is 16.9771\n",
      "Epoch 1, loss is 0.7747\n",
      "Epoch 2, loss is 0.0380\n",
      "Epoch 3, loss is 0.0043\n",
      "Epoch 4, loss is 0.0026\n",
      "Epoch 5, loss is 0.0023\n",
      "Epoch 6, loss is 0.0022\n",
      "Epoch 7, loss is 0.0020\n",
      "Epoch 8, loss is 0.0019\n",
      "Epoch 9, loss is 0.0017\n"
     ]
    }
   ],
   "source": [
    "model = SimpleLinear()\n",
    "opt = Optimizer(model.parameters(), lr=0.3)\n",
    "\n",
    "for epoch in range(10):\n",
    "    output = model(x_train)\n",
    "    loss = loss_func(y_train, output)\n",
    "    loss.backward()\n",
    "    opt.step()\n",
    "    opt.zero_grad()\n",
    "    print('Epoch {}, loss is {:.4f}'.format(epoch, loss.item()))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
